<?php

namespace app\store\controller;

use app\store\model\User as UserModel;
use app\store\model\user\Grade as GradeModel;
use think\Db;
use think\Log;

/**
 * 用户管理
 * Class User
 * @package app\store\controller
 */
class User extends Controller
{
    /**
     * 用户列表
     * @param string $nickName 昵称
     * @param int $gender 性别
     * @param int $grade 会员等级
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function index($nickName = '', $gender = null, $grade = null, $shanghui = null)
    {
        $model = new UserModel;
        $list = $model->getList($nickName, $gender, $grade, $shanghui);
        foreach ($list as $value) {
            $value['shanghui_name'] = Db::name('shanghui')->where('id', $value['shanghui_id'])->value('name') ?? '暂无商会';
        }
        $team = Db::name('team')->where('wxapp_id', self::getWxappId())->select()->toArray();
        $shanghui = Db::name('shanghui')->where('wxapp_id', self::getWxappId())->select()->toArray();
        // 会员等级列表
        $gradeList = GradeModel::getUsableList();
        return $this->fetch('index', compact('list', 'gradeList', 'grade', 'team', 'shanghui'));
    }

    public function olduser()
    {
        $param = input('param.');
        $where = [];
        if (!empty($param['nickName'])) {
            $where = ['name' => ['like', '%' . $param['nickName'] . '%']];
        }
        if (!empty($param['card_id'])) {
            $where = ['card_id' => ['like', '%' . $param['card_id'] . '%']];
        }
        if (!empty($param['card_id']) && !empty($param['nickName'])) {
            $where = ['card_id' => ['like', '%' . $param['card_id'] . '%'], 'name' => ['like', '%' . $param['nickName'] . '%']];
        }
        $list = Db::name('old_user')->where($where)->where('wxapp_id', self::getWxappId())->paginate(15, false, [
            'query' => \request()->request()
        ])->each(function ($item) {
            $item['donate'] = Db::name('old_donate')->where('vip_number', $item['vip_number'])->value('donate_total') ?? 0;
            $item['team_name_old'] = Db::name('team')->where('team_id', $item['team_id'])->value('team_name') ?? '暂无服务队';
            return $item;
        });
        //var_dump($list);die();
        return $this->fetch('olduser', compact('list'));
    }

    //新会员申请列表
    public function newuser()
    {
        $param = input('param.');
        $where = [];
        if (!empty($param['nickName'])) {
            $where = ['name' => ['like', '%' . $param['nickName'] . '%']];
        }
        if (!empty($param['card_id'])) {
            $where = ['card_id' => ['like', '%' . $param['card_id'] . '%']];
        }
        if (!empty($param['card_id']) && !empty($param['nickName'])) {
            $where = ['card_id' => ['like', '%' . $param['card_id'] . '%'], 'name' => ['like', '%' . $param['nickName'] . '%']];
        }
        $list = Db::name('apply_member')->where($where)->where('wxapp_id', self::getWxappId())->paginate(15, false, [
            'query' => \request()->request()
        ])->each(function ($item) {
            $item['team_name'] = Db::name('team')->where('team_id', $item['team_id'])->value('team_name') ?? '';
            if ($item['examine_uid'] > 0) {
                $item['user'][] = Db::name('user')->where('user_id', $item['examine_uid'])->find();
            } else {
                $item['user']['nickName'] = '';
                $item['user']['user_id'] = 0;
            }
            return $item;
        });
        //var_dump($list);die();
        return $this->fetch('newuser', compact('list'));
    }

    //新会员入会申请审核
    public function newExamine()
    {
        $param = input('param.');
        Db::startTrans();
        try {
            Db::name('apply_member')->where('id', $param['id'])
                ->update([
                    'examine_status' => $param['examine_status'],
                    'examine_time' => date('Y-m-d H:i:s'),
                    'examine_remark' => $param['examine_remark'],
                ]);
            if (intval($param['examine_status']) == 1) {//审核通过插入老会员表方可认领身份
                $data = Db::name('apply_member')->where('id', $param['id'])->find();
                $team = Db::name('team')->where('team_id', $data['team_id'])->find();
                Db::name('old_user')->insert([
                    'team_name' => $team['team_name'],
                    'team_num' => $team['team_no'],
                    'name' => $data['name'],
                    'gender' => $data['gender'],
                    'birth_date' => $data['birth_date'],
                    'phone' => $data['phone'],
                    'company_name' => $data['company'],
                    'duties' => $data['duties'],
                    'card_id' => $data['card_id'],
                    'education' => $data['education'],
                    'team_id' => $data['team_id'],
                    'referee' => $data['referee'],
                    'address' => $data['address'],
                    'politics' => $data['politics'],
                    'hometown' => $data['hometown'],
                    'nation' => $data['nation'],
                    'add_date' => date('Y') . '-01-01'
                ]);
            }
            Db::commit();
            return $this->renderSuccess('操作成功');
        } catch (\Exception $e) {
            Db::rollback();
            return $this->renderError($e->getMessage() ?: '操作失败');
        }
    }

    //申请详情
    public function detail($user_id)
    {
        //var_dump(12413);die();
        $model = Db::name('apply_member')->where('user_id', $user_id)->find();
        if ($model['carda_id'] != 0) {
            $a = Db::name('upload_file')->find($model['carda_id']);
            $model['image_a'] = $a['file_url'] . '/' . $a['file_name'];
        }
        if ($model['cardb_id'] != 0) {
            $b = Db::name('upload_file')->find($model['cardb_id']);
            $model['image_b'] = $b['file_url'] . '/' . $b['file_name'];
        }
        $model['team_name'] = Db::name('team')->where('team_id', $model['team_id'])->value('team_name') ?? '';
        $info_second = Db::name('apply_member_secondary')->where('user_id', $user_id)->find();
        return $this->fetch('detail', compact('model', 'info_second'));
    }

    /**
     * 添加老会员
     * @return array|mixed
     */
    public function add()
    {
        if (!$this->request->isAjax()) {
            $team = Db::name('team')->where('wxapp_id', self::getWxappId())->select()->toArray();
            return $this->fetch('add', compact('team'));
        }
        // 新增记录
        $param = input('param.');
        if (!$param['vip_number']) {
            $param['vip_number'] = uniqid();//不填vip号给个随机
        }
        $res5 = Db::name('old_user')->where('vip_number', $param['vip_number'])->where('wxapp_id', self::getWxappId())->find();
        $res6 = Db::name('old_user')->where('card_id', $param['card_id'])->where('wxapp_id', self::getWxappId())->find();
        if ($res5 || $res6) {
            return $this->renderError('添加失败，会员号/身份证号已存在');
        }

        $team_info = Db::name('team')->where('wxapp_id', self::getWxappId())->where('team_id', $param['team']['team_id'])->find();
        if (!$team_info) {
            $team_info['team_no'] = 0;
            $team_info['team_name'] = '暂无服务队';
            $team_info['team_id'] = 0;
            $param['team_num'] = 0;
            $param['team_name'] = '暂无服务队';
        }
        $res2 = Db::name('old_donate')->where('vip_number', $param['vip_number'])->where('wxapp_id', self::getWxappId())->find();
        if ($res2) {
            Db::name('old_donate')
                ->where('vip_number', $param['vip_number'])
                ->where('wxapp_id', self::getWxappId())
                ->update([
                    'team_num' => $team_info['team_no'],
                    'team_name' => $team_info['team_name'],
                    'donate_total' => $param['donate'],
                    'vip_number' => $param['vip_number'],
                    'team_id' => $param['team']['team_id'],
                ]);
        } else {
            Db::name('old_donate')->insert([
                'team_name' => $team_info['team_name'],
                'team_num' => $team_info['team_no'],
                'vip_number' => $param['vip_number'],
                'team_id' => $param['team']['team_id'],
                'name' => $param['name'],
                'service_total' => 0,
                'politics_total' => 0,
                'invisible_total' => 0,
                'donate_total' => $param['donate'],
                'wxapp_id' => self::getWxappId()
            ]);
        }
        $param['team_id'] = $team_info['team_id'];
        $param['team_num'] = $team_info['team_no'];
        $param['team_name'] = $team_info['team_name'];
        unset($param['donate']);
        unset($param['team']);
        $param['wxapp_id'] = self::getWxappId();
        $res = Db::name('old_user')->insert($param);
        if ($res) {
            return $this->renderSuccess('添加成功', url('user/olduser'));
        }
        return $this->renderError('添加失败');
    }

    /**
     * 编辑老会员
     * @param $article_id
     * @return array|mixed
     * @throws \think\exception\DbException
     */
    public function edit($user_id)
    {
        // 文章详情
        $team = Db::name('team')->where('wxapp_id', self::getWxappId())->select()->toArray();
        $model = Db::name('old_user')->find($user_id);
        $model['donate'] = Db::name('old_donate')->where('vip_number', $model['vip_number'])->where('wxapp_id', self::getWxappId())->value('donate_total') ?? 0;
        if (!$this->request->isAjax()) {
            return $this->fetch('edit', compact('model', 'team'));
        }
        // 更新记录
        $param = input('param.');
        $team_info = Db::name('team')->where('wxapp_id', self::getWxappId())->where('team_id', $param['team']['team_id'])->find();
        if (!$team_info) {
            $team_info['team_no'] = 0;
            $team_info['team_name'] = '暂无服务队';
        }
        //var_dump($param);die();
        Db::startTrans();
        try {
            $res2 = Db::name('old_donate')->where('vip_number', $model['vip_number'])->where('wxapp_id', self::getWxappId())->find();
            if ($res2) {
                Db::name('old_donate')
                    ->where('vip_number', $model['vip_number'])
                    ->where('wxapp_id', self::getWxappId())
                    ->update([
                        'team_num' => $team_info['team_no'],
                        'name' => $param['name'],
                        'team_name' => $team_info['team_name'],
                        'donate_total' => $param['donate'],
                        'vip_number' => $param['vip_number'],
                        'team_id' => $param['team']['team_id'],
                    ]);
            } else {
                Db::name('old_donate')->insert([
                    'team_name' => $team_info['team_name'],
                    'team_num' => $team_info['team_no'],
                    'vip_number' => $param['vip_number'],
                    'team_id' => $param['team']['team_id'],
                    'name' => $param['name'],
                    'service_total' => 0,
                    'politics_total' => 0,
                    'invisible_total' => 0,
                    'donate_total' => $param['donate'],
                    'wxapp_id' => self::getWxappId()
                ]);
            }
            $res = Db::name('old_user')->where('user_id', $user_id)->update([
                'team_name' => $team_info['team_name'],
                'team_num' => $team_info['team_no'],
                'team_id' => $param['team']['team_id'],
                'name' => $param['name'],
                'gender' => $param['gender'],
                'vip_number' => $param['vip_number'],
                'phone' => $param['phone'],
                'add_date' => $param['add_date'],
                'card_id' => $param['card_id'],
                'status' => $param['status'],
                'wxapp_id' => self::getWxappId()
            ]);

            $data_new = Db::name('old_user')->where('user_id', $user_id)->find();
            $donate_new = Db::name('old_donate')->where('vip_number', $data_new['vip_number'])->find();
            if ($data_new && $data_new['user_uid'] > 0) {
                Db::name('user')->where('user_id', $data_new['user_uid'])->update([
                    'team_id' => $data_new['team_id'],
                    'nickName' => $data_new['name'],
                    'gender' => $data_new['gender'],
                    'vip_number' => $data_new['vip_number'],
                    'phone' => $data_new['phone'],
                    'add_date' => $data_new['add_date'],
                    'card_id' => $data_new['card_id'],
                    'donate' => $donate_new['donate_total']
                ]);
            }
            Log::record("为防止编辑后不承认现象，特写日志->编辑数据：名字：" . $param['name'] . "会员号：" . $param['vip_number'] . "编辑时间：" . date('Y-m-d H:i:s'));
            Db::commit();
            return $this->renderSuccess('更新成功', url('user/olduser'));
        } catch (\Exception $e) {
            Db::rollback();
            return $this->renderError($e->getMessage() . '更新失败');
        }
//        if ($res) {
//            return $this->renderSuccess('更新成功', url('user/olduser'));
//        }
//        return $this->renderError($model->getError() ?: '更新失败');
    }


    //做一些二逼的操作临时用
    public function bigerbi()
    {
        var_dump(111222);
        die();
        $a = Db::name('old_donate')->where('vip_number', 5980561)->select()->toArray();
        foreach ($a as $value) {
            $b = Db::name('old_user')->where('name', $value['name'])->find();
            if ($b) {
                Db::name('old_donate')->where('name', $b['name'])->update([
                    'team_name' => $b['team_name'],
                    'vip_number' => $b['vip_number'],
                    'team_num' => $b['team_num'],
                    'team_id' => $b['team_id'],
                ]);
            }
        }
    }

    /**
     * 删除用户
     * @param $user_id
     * @return array
     * @throws \think\exception\DbException
     */
    public function delete($user_id)
    {
        // 用户详情
        $model = UserModel::detail($user_id);
        if ($model->setDelete()) {
            return $this->renderSuccess('删除成功');
        }
        return $this->renderError($model->getError() ?: '删除失败');
    }

    /**
     * 用户充值
     * @param $user_id
     * @param int $source 充值类型
     * @return array|bool
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function recharge($user_id, $source)
    {
        // 用户详情
        $model = UserModel::detail($user_id);
        if ($model->recharge($this->store['user']['user_name'], $source, $this->postData('recharge'))) {
            return $this->renderSuccess('操作成功');
        }
        return $this->renderError($model->getError() ?: '操作失败');
    }

    /**
     * 修改会员等级
     * @param $user_id
     * @return array|bool
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function grade($user_id)
    {
        // 用户详情
        $model = UserModel::detail($user_id);
        if ($model->updateGrade($this->postData('grade'))) {
            return $this->renderSuccess('操作成功');
        }
        return $this->renderError($model->getError() ?: '操作失败');
    }

    /**
     * 修改审核权限
     * @param $user_id
     * @return array|bool
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function examine($user_id)
    {
        // 用户详情
        $examine_role = input('param.examine_role');
        $model = UserModel::detail($user_id);
        if ($model->updateExamine($examine_role)) {
            return $this->renderSuccess('操作成功');
        }
        return $this->renderError($model->getError() ?: '操作失败');
    }

}
